﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using Microsoft.SharePoint;
using CreditAgricole.Framework;

namespace CreditAgricole.Application
{
    public static class DataKnowledgeBase
    {
        /// <summary>
        /// Get all items in list
        /// </summary>
        /// <param name="siteId">Current site ID</param>
        /// <param name="webId">Current web ID</param>
        /// <param name="listTitle">List title where tasks were created</param>
        /// <returns>List of MepObj</returns>
        public static List<VOBase> GetKBaseObj(Guid siteId, Guid webId, string listTitle)
        {
            List<VOBase> kbaseObjs = new List<VOBase>();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(siteId))
                {
                    using (SPWeb web = site.OpenWeb(webId))
                    {
                        SPList list = web.Lists.TryGetList(listTitle);
                        if (list != null)
                        {
                            SPQuery query = QueryBuilder.GetSelectedItemsOrderBy(Constants.CreatedDateField);
                            SPListItemCollection items = list.GetItems(query);
                            AddItemsToMepList(kbaseObjs, items);
                        }
                    }
                }
            });
            return kbaseObjs;
        }

        /// <summary>
        /// Get items created by specific user
        /// </summary>
        /// <param name="siteId">Current site ID</param>
        /// <param name="webId">Current web ID</param>
        /// <param name="listTitle">List title where documents were created</param>
        /// <param name="currentUserId">User</param>
        /// <returns>List of MepObj</returns>
        public static List<VOBase> GetMyKBase(Guid siteId, Guid webId, string listTitle, int currentUserId)
        {
            List<VOBase> kbaseObjs = new List<VOBase>();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(siteId))
                {
                    using (SPWeb web = site.OpenWeb(webId))
                    {
                        SPList list = web.Lists.TryGetList(listTitle);
                        if (list != null)
                        {
                            SPQuery query = QueryBuilder.GetSelectedItemsWithLookup("Lookup", "Author", MappingTool.CatchNull(currentUserId));
                            SPListItemCollection items = list.GetItems(query);
                            AddItemsToMepList(kbaseObjs, items);
                        }
                    }
                }
            });
            return kbaseObjs;
        }
        #region Tool Methods

        /// <summary>
        /// Insert map all items and insert them in MepObjs list
        /// </summary>
        /// <param name="kbaseObjs">MepObjs List</param>
        /// <param name="items">Items to map</param>
        private static void AddItemsToMepList(List<VOBase> kbaseObjs, SPListItemCollection items)
        {
            try
            {
                foreach (SPListItem item in items)
                {
                    VOKnowledgeBase kbaseObj = GetMappedObj(item);
                    kbaseObjs.Add(kbaseObj);
                }
            }
            catch (SPException ex)
            {
                CALoggingHelper.AddErrorEntry(ex.Message);
            }
        }

        /// <summary>
        /// Map object from List item
        /// </summary>
        /// <param name="item">List item</param>
        /// <returns>mapped object</returns>
        private static VOKnowledgeBase GetMappedObj(SPListItem item)
        {
            VOKnowledgeBase kbaseObj = VOMapperKnowledgeBase.GetVOBKnowledgeFromListItem(item);
            kbaseObj.Author = (GetSPUser(item, Constants.AuthorField) != null ? GetSPUser(item, Constants.AuthorField).User.Name : string.Empty);
            kbaseObj.Product = GetLookupValueFromItem(item,Constants.ProductField);
            kbaseObj.DocType = GetLookupValueFromItem(item, Constants.DocTypeField);
            kbaseObj.Audience = GetLookupValuesFromItem(item, Constants.AudienceField);
            kbaseObj.Keywords = GetLookupValuesFromItem(item, Constants.KeyWordsField);
            return kbaseObj;
        }

        /// <summary>
        /// Get the SPUser object from Item 
        /// </summary>
        /// <param name="item">Item from the list</param>
        /// <param name="fieldName">field name containing the user</param>
        /// <returns>SPUser objectof the specified item</returns>
        private static SPFieldUserValue GetSPUser(SPListItem item, string fieldName)
        {
            SPFieldUserValue fieldValue = null;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPFieldUser field = item.Fields.GetField(fieldName) as SPFieldUser;
                    if (field != null && item[fieldName] != null)
                    {
                        fieldValue = field.GetFieldValue(MappingTool.CatchNull(item[fieldName])) as SPFieldUserValue;
                    }
                });
            }
            catch (SPException ex)
            {
                CALoggingHelper.AddErrorEntry(ex.Message);
            }
            return fieldValue;
        }


        private static string GetLookupValueFromItem(SPListItem item, string fieldName)
        {
            string selectedValue = string.Empty;
            SPFieldLookup field = item.Fields.GetField(fieldName) as SPFieldLookup;
            if (item[fieldName] != null && field != null)
            {
                SPFieldLookupValue valueField = field.GetFieldValue(MappingTool.CatchNull(item[fieldName])) as SPFieldLookupValue;
                selectedValue = valueField.LookupValue;
            }
            return selectedValue;
        }

        private static List<string> GetLookupValuesFromItem(SPListItem item, string fieldName)
        {
            List<string> entities = new List<string>();
            if (item[fieldName] != null)
            {
                SPFieldLookupValueCollection valuesField = item[fieldName] as SPFieldLookupValueCollection;
                foreach (SPFieldLookupValue value in valuesField)
                {
                    entities.Add(value.LookupValue);
                }
            }
            return entities;
        }

        #endregion

    }
}
